package com.zx.mes.coolmq.hyl.annotation;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zx.mes.coolmq.hyl.sender.RabbitmqSender;
import com.zx.mes.coolmq.hyl.util.MqConstants;
import com.zx.mes.coolmq.hyl.util.RabbitMetaMessage;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 封装sender
 * @author hyl
 * @date 2018-3-19
 * @version 1.0.0
 */
@Component
@Aspect
public class SenderWraper {

    private static final Logger logger = LoggerFactory.getLogger(SenderWraper.class);

    @Autowired
    private RabbitmqSender rabbitmqSender;

    /**  定义注解类型的切点，只要方法上有该注解，都会匹配  */
    @Pointcut("@annotation(com.zx.mes.coolmq.hyl.annotation.MqSender)")
    public void annotationSender(){
    }

    public void sendMsg(ProceedingJoinPoint joinPoint,MqSender args) throws Throwable {

        /**
         * annotation中的exchange和queue 不得为空
         */
        if (joinPoint.getArgs().length != 1 && joinPoint.getArgs()[0] == null) {
            logger.error("senderWraper args is null");
        }
        String exchange=args.exchange();
        String routingKey = args.routingKey();

        /**
         * 执行业务函数
         */
        Object resultObj = joinPoint.proceed();
        if (resultObj == null) {
            resultObj = MqConstants.BLANK_STR;
        }

        /**
         * 生成一个发送对象
         */
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();

        /**
         * 设置交换机
         */
        rabbitMetaMessage.setExchange(exchange);

        /**
         * 指定routing key
         */
        rabbitMetaMessage.setRoutingKey(routingKey);

        /**
         * 设置需要传递的消息体，可以是任意对象
         */
        rabbitMetaMessage.setPayload(resultObj);

        /**
         * 发送消息
         */
        try {
            rabbitmqSender.send(rabbitMetaMessage);
        } catch (Exception e) {
           logger.error("消息发送异常" + e.toString());
           throw e;
        }

    }


}
